package Socketserver;

import Public.SocketResult;
import Socketserver.Socket.SocketServer;

import java.io.*;
import java.net.Socket;
import java.nio.file.Files;
import java.nio.file.Paths;

public class TestCenterSocket {
    // 移除static，改为实例变量
    private SocketServer server = new SocketServer();
    private final int PORT = 8080; // 保留final（常量），移除static
    private final String TEST_FILE_PATH = "test_send.txt";
    private final String CLIENT_SAVE_PATH = "client_received.txt";
    private final String SERVER_BASE_PATH = "D:\\a_E\\桌面\\IdeaProjects\\IdeaProjects\\WHAT_JAVA_HOMEWORK_FOR_CLASS\\src\\aTXT_pagage\\";

    // 移除static，改为实例方法
    public void function() {
        try {
            // 1. 测试服务器创建
            testServerCreate();

            // 2. 测试字符串接收功能
            testReceiveString();
            Thread.sleep(500); // 等待资源释放

            // 3. 测试文件接收功能
            testReceiveFile();
            Thread.sleep(500);

            // 4. 测试字符串输出功能
            testSendString();
            Thread.sleep(500);

            // 5. 测试文件输出（下载）功能
            testSendFile();
            Thread.sleep(500);

            // 6. 测试用户ID接收与权限校验输出
            testUserAuth();
            Thread.sleep(500);

            // 7. 测试服务器关闭
            testServerClose();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 1. 测试服务器创建（移除static）
    private void testServerCreate() throws IOException {
        System.out.println("\n=== 测试服务器创建 ===");
        boolean isCreated = server.ServerSocket_CREATE_Socket();
        if (isCreated) {
            System.out.println("服务器创建测试通过");
            System.out.println("ServerSocket_CREATE_Socket方法成功"); // 新增成功提示
        } else {
            System.out.println("服务器创建测试失败");
        }
    }

    // 2. 测试字符串接收（移除static）
    private void testReceiveString() throws InterruptedException {
        System.out.println("\n=== 测试字符串接收 ===");
        // 服务器接收线程
        Thread serverThread = new Thread(() -> {
            try {
                SocketResult result = server.ServerSocket_INPUT("STRING");
                System.out.println("服务器接收结果：" + (result != null ? result.getMessage() : "结果为空"));
                if (result != null && result.isSuccess()) {
                    System.out.println("接收的字符串内容：" + result.getData());
                    System.out.println("ServerSocket_INPUT_STRING方法成功"); // 新增成功提示
                }
            } catch (IOException e) {
                System.err.println("服务器接收字符串异常：" + e.getMessage());
            }
        });
        serverThread.start();

        // 客户端发送线程
        Thread clientThread = new Thread(() -> {
            try (Socket socket = new Socket("localhost", PORT);
                 DataOutputStream dos = new DataOutputStream(socket.getOutputStream())) {
                String sendData = "测试字符串：Hello Socket Server!";
                dos.writeUTF(sendData);
                dos.flush();
                System.out.println("客户端已发送字符串：" + sendData);
            } catch (IOException e) {
                System.err.println("客户端发送字符串异常：" + e.getMessage());
            }
        });
        clientThread.start();

        serverThread.join();
        clientThread.join();
    }

    // 3. 测试文件接收（移除static）
    private void testReceiveFile() throws InterruptedException, IOException {
        System.out.println("\n=== 测试文件接收 ===");
        // 准备测试文件
        Files.write(Paths.get(TEST_FILE_PATH), "测试文件内容：Socket传输测试".getBytes());

        // 服务器接收线程
        Thread serverThread = new Thread(() -> {
            try {
                SocketResult result = server.ServerSocket_INPUT("FILE");
                System.out.println("服务器文件接收结果：" + (result != null ? result.getMessage() : "结果为空"));
                if (result != null && result.isSuccess()) {
                    System.out.println("文件保存路径：" + result.getData());
                    System.out.println("ServerSocket_INPUT_FILE方法成功"); // 新增成功提示
                }
            } catch (IOException e) {
                System.err.println("服务器接收文件异常：" + e.getMessage());
            }
        });
        serverThread.start();

        // 客户端发送线程
        Thread clientThread = new Thread(() -> {
            try (Socket socket = new Socket("localhost", PORT);
                 DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
                 FileInputStream fis = new FileInputStream(TEST_FILE_PATH)) {

                File file = new File(TEST_FILE_PATH);
                dos.writeUTF(file.getName()); // 发送文件名
                dos.writeLong(file.length()); // 发送文件大小

                // 发送文件内容
                byte[] buffer = new byte[1024];
                int len;
                while ((len = fis.read(buffer)) != -1) {
                    dos.write(buffer, 0, len);
                }
                dos.flush();
                System.out.println("客户端已发送文件：" + file.getName() + "（大小：" + file.length() + "字节）");

            } catch (IOException e) {
                System.err.println("客户端发送文件异常：" + e.getMessage());
            }
        });
        clientThread.start();

        serverThread.join();
        clientThread.join();
        // 清理测试文件
        Files.deleteIfExists(Paths.get(TEST_FILE_PATH));
    }

    // 4. 测试字符串输出（移除static）
    private void testSendString() throws InterruptedException {
        System.out.println("\n=== 测试字符串输出 ===");
        // 服务器发送线程
        Thread serverThread = new Thread(() -> {
            try {
                SocketResult result = server.ServerSocket_OUTPUT_OUTPUT();
                System.out.println("服务器发送字符串结果：" + (result != null ? result.getMessage() : "结果为空"));
                if (result != null && result.isSuccess()) {
                    System.out.println("ServerSocket_OUTPUT_OUTPUT_String方法成功"); // 新增成功提示
                }
            } catch (IOException e) {
                System.err.println("服务器发送字符串异常：" + e.getMessage());
            }
        });
        serverThread.start();

        // 客户端接收线程
        Thread clientThread = new Thread(() -> {
            try (Socket socket = new Socket("localhost", PORT);
                 DataInputStream dis = new DataInputStream(socket.getInputStream())) {

                String received = dis.readUTF();
                System.out.println("客户端接收的字符串：" + received);

            } catch (IOException e) {
                System.err.println("客户端接收字符串异常：" + e.getMessage());
            }
        });
        clientThread.start();

        serverThread.join();
        clientThread.join();
    }

    // 5. 测试文件输出（下载）（移除static）
    private void testSendFile() throws InterruptedException, IOException {
        System.out.println("\n=== 测试文件输出（下载） ===");
        // 准备服务器测试文件（使用与SocketServer一致的基础路径）
        String serverFilePath = SERVER_BASE_PATH + "test_download.txt";
        Files.createDirectories(Paths.get(SERVER_BASE_PATH)); // 确保目录存在
        Files.write(Paths.get(serverFilePath), "服务器测试文件：用于下载测试".getBytes());

        // 服务器发送线程
        Thread serverThread = new Thread(() -> {
            try {
                server.ServerSocket_OUTPUT_CREATE_Socket(); // 创建输出连接
                boolean isSent = server.ServerSocket_OUTPUT_OUTPUT_download();
                System.out.println("服务器文件发送结果：" + (isSent ? "成功" : "失败"));
                if (isSent) {
                    System.out.println("ServerSocket_OUTPUT_OUTPUT_download方法成功"); // 新增成功提示
                }
            } catch (IOException e) {
                System.err.println("服务器发送文件异常：" + e.getMessage());
            }
        });
        serverThread.start();

        // 客户端接收线程
        Thread clientThread = new Thread(() -> {
            try (Socket socket = new Socket("localhost", PORT);
                 DataInputStream dis = new DataInputStream(socket.getInputStream());
                 FileOutputStream fos = new FileOutputStream(CLIENT_SAVE_PATH)) {

                // 读取服务器发送的文件元数据
                String type = dis.readUTF();
                if ("FILE".equals(type)) {
                    String fileName = dis.readUTF();
                    long fileSize = dis.readLong();

                    // 接收文件内容
                    byte[] buffer = new byte[1024];
                    int len;
                    long totalRead = 0;
                    while (totalRead < fileSize && (len = dis.read(buffer)) != -1) {
                        fos.write(buffer, 0, len);
                        totalRead += len;
                    }
                    System.out.println("客户端接收文件完成：" + fileName + "（保存路径：" + CLIENT_SAVE_PATH + "）");
                }

            } catch (IOException e) {
                System.err.println("客户端接收文件异常：" + e.getMessage());
            }
        });
        clientThread.start();

        serverThread.join();
        clientThread.join();
        // 清理测试文件
        Files.deleteIfExists(Paths.get(serverFilePath));
        Files.deleteIfExists(Paths.get(CLIENT_SAVE_PATH));
    }

    // 6. 测试用户ID接收与权限校验（修正后）
    private void testUserAuth() throws InterruptedException {
        System.out.println("\n=== 测试用户ID接收与权限校验 ===");
        // 服务器处理线程（修正连接建立方式）
        Thread serverThread = new Thread(() -> {
            try {
                // 直接建立连接，不触发字符串接收（移除原ServerSocket_INPUT("STRING")）
                if (server.server == null || server.server.isClosed()) {
                    System.out.println("服务器未启动，无法建立连接");
                    return;
                }
                // 直接接收客户端连接
                server.clientSocket = server.server.accept();
                // 初始化输入输出流
                server.dis = new DataInputStream(server.clientSocket.getInputStream());
                server.dos = new DataOutputStream(server.clientSocket.getOutputStream());
                System.out.println("用户权限校验：客户端连接成功");

                // 接收用户ID（此时不会被其他readUTF()阻塞）
                SocketResult idResult = server.ServerSocket_INPUT_USERID();
                System.out.println("用户ID接收结果：" + (idResult != null ? idResult.getMessage() : "结果为空"));
                if (idResult != null && idResult.isSuccess()) {
                    String userId = (String) idResult.getData();
                    System.out.println("ServerSocket_INPUT_USERID方法成功"); // 新增成功提示
                    String authMsg = "用户[" + userId + "]权限校验通过：允许访问";
                    // 发送权限结果
                    SocketResult authResult = server.ServerSocket_OUTPUT_USER_AUTH(authMsg);
                    System.out.println("权限结果发送：" + (authResult != null ? authResult.getMessage() : "结果为空"));
                    if (authResult != null && authResult.isSuccess()) {
                        System.out.println("ServerSocket_OUTPUT_USER_AUTH方法成功"); // 新增成功提示
                    }
                }
            } catch (IOException e) {
                System.err.println("服务器权限校验异常：" + e.getMessage());
            }
        });
        serverThread.start();

        // 客户端发送线程（保持不变）
        Thread clientThread = new Thread(() -> {
            try (Socket socket = new Socket("localhost", PORT);
                 DataInputStream dis = new DataInputStream(socket.getInputStream());
                 DataOutputStream dos = new DataOutputStream(socket.getOutputStream())) {

                // 发送用户ID
                String userId = "test_user_123";
                dos.writeUTF(userId);
                dos.flush();
                System.out.println("客户端已发送用户ID：" + userId);

                // 接收权限结果
                String authResult = dis.readUTF();
                System.out.println("客户端接收权限结果：" + authResult);

            } catch (IOException e) {
                System.err.println("客户端权限校验异常：" + e.getMessage());
            }
        });
        clientThread.start();

        serverThread.join();
        clientThread.join();
    }

    // 7. 测试服务器关闭（移除static）
    private void testServerClose() throws IOException {
        System.out.println("\n=== 测试服务器关闭 ===");
        boolean isClosed = server.ServerSocket_CLOSE();
        if (isClosed) {
            System.out.println("服务器关闭测试通过");
            System.out.println("ServerSocket_CLOSE方法成功"); // 新增成功提示
        } else {
            System.out.println("服务器关闭测试失败");
        }
    }
}